package com.yueqianshop.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.yueqianshop.product.service.CategoryBrandRelationService;
import com.yueqianshop.product.vo.Catalog2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yueqianshop.common.utils.PageUtils;
import com.yueqianshop.common.utils.Query;

import com.yueqianshop.product.dao.CategoryDao;
import com.yueqianshop.product.entity.CategoryEntity;
import com.yueqianshop.product.service.CategoryService;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    RedissonClient redisson;

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths= new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);
        Collections.reverse(parentPath);//因为获取到的顺序是倒叙的数组，所以要倒过来排。
        return  paths.toArray(new Long[parentPath.size()]);
    }

    private List<Long> findParentPath(Long catelogId, List<Long> paths){
        //1、收集当前节点id
        paths.add(catelogId);
        CategoryEntity byId =this.getById(catelogId);
        if (byId.getParentCid()!=0){
            findParentPath(byId.getParentCid(),paths);
        }
        return paths;
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1、注入查categoryDao询出所有的分类信息，
        List<CategoryEntity> entities = baseMapper.selectList(null);
        //2、组装成父子的树形结构
        //2.1找出所有一级分类：
        List<CategoryEntity> level1Menus = entities.stream().filter((categoryEntity) -> {
            return categoryEntity.getParentCid() !=null && categoryEntity.getParentCid() == 0;
        }).map((menu) -> {
            menu.setChildren(getChildrens(menu, entities));
            return menu;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return level1Menus;
    }
    //递归查找所有菜单的子菜单,这段代码真的脑阔疼😭😭😓
    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> children = all.stream().filter((categoryEntity) -> {
            return categoryEntity.getParentCid() == root.getCatId();
        }).map(categoryEntity -> {
            //1、找到子菜单
            categoryEntity.setChildren(getChildrens(categoryEntity, all));
            return categoryEntity;
        }).sorted((menu1, menu2) -> {
            //2、菜单的排序
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return children;
    }



    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        baseMapper.deleteBatchIds(asList);
    }


//    @Caching(evict = {
//            @CacheEvict(value = "category",key = "'getLevel1Catagories'"),
//            @CacheEvict(value = "category",key = "'getCatalogJson'")
//    })
    @CacheEvict(value = "category",allEntries = true)
    @Override
    public void updateCascade(CategoryEntity category) {
        //通过id更新自己
        this.updateById(category);
        //更新关联表里面的数据，注入关联表对象
        categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
    }







    @Cacheable(value = {"category"},key = "#root.method.name")
    @Override
    public List<CategoryEntity> getLevel1Catagories() {
        System.out.println("1111111111111111111111");
        List<CategoryEntity> list = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return list;
    }

    @Cacheable(value = "category",key = "#root.method.name")
    public Map<String, List<Catalog2Vo>> getCatalogJson() {
        System.out.println("重新查询了数据库");
        //将数据库多次查询变为1此
        List<CategoryEntity> selectList = this.baseMapper.selectList(null);
        //查出所有1级分类
        List<CategoryEntity> level1Category = getLevel1Catagories();
        //2、封装数据
        Map<String, List<Catalog2Vo>> parent_cid = level1Category.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //1、每一个的一级分类，查到这个一级分类的二级分类
            List<CategoryEntity> categoryEntities = getParentCid(selectList, v.getCatId());
            //2、封装上面的结果
            List<Catalog2Vo> catalog2Vos = null;
            if (categoryEntities != null) {
                catalog2Vos = categoryEntities.stream().map(l2 -> {
                    Catalog2Vo catalog2Vo = new Catalog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    //1、找当前二级分类的三级分类封装vo
                    List<CategoryEntity> level3Catalog = getParentCid(selectList, l2.getCatId());
                    if (level3Catalog != null) {
                        List<Catalog2Vo.Catalog3Vo> collect = level3Catalog.stream().map(l3 -> {
                            //2、封装成指定格式
                            Catalog2Vo.Catalog3Vo catalog3Vo = new Catalog2Vo.Catalog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catalog3Vo;
                        }).collect(Collectors.toList());
                        catalog2Vo.setCatalog3List(collect);
                    }
                    return catalog2Vo;
                }).collect(Collectors.toList());
            }
            return catalog2Vos;
        }));

        return parent_cid;

    }




    public Map<String, List<Catalog2Vo>> getCatalogJson1() {
        //给缓存中放json字符串，拿出json字符串，还要逆转为能用的对象类型【序列化与反序列化】
        //JSON好处是跨语言，跨平台兼容。
        //1.获取 字符串类型 对象 并通过keycatalogJSON ,获取redis中保存数据
        String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");
        //2.判断是否位空  为空 redis中没有数据 ,需要从数据库查询
        if(StringUtils.isEmpty(catalogJSON)){
            //数据库中查询数据
            Map<String, List<Catalog2Vo>> datafromDB = getDatafromDBWithLocalhostRedissonLock();
            //将查到的数据再放入缓存，将对象转为JSON在缓存中
            String jsonString = JSON.toJSONString(datafromDB);
            redisTemplate.opsForValue().set("catalogJSON",jsonString);
            return datafromDB;
        }
        //如果缓存中存在 将字符串数据转为 Map集合返回
        return JSON.parseObject(catalogJSON,new TypeReference<Map<String, List<Catalog2Vo>>>(){});
    }

    public Map<String, List<Catalog2Vo>> getDatafromDBWithLocalhostRedissonLock() {

        //1.锁的名字.粒度越细,越快
        //锁的粒度: 如果具体锁的是某个数据 如11号商品 锁的名字 应为  product-11-lock 12号商品锁名为 product-12-lock
        RLock lock = redisson.getLock("catalogJSON-lock");
        lock.lock();//加锁
        Map<String, List<Catalog2Vo>> dataFromDB;
        try {
            dataFromDB= getDatafromDB();
        }finally {
            lock.unlock();
        }
        return dataFromDB;
    }

    public Map<String, List<Catalog2Vo>> getDatafromDB() {

        //只要是同一把锁，就能锁住需要这个锁的所有线程
        //1、synchronized (this)：Springboot所有的组件在容器中都是单例的，所以即使有100万并发进来，
        // 调CategoryServiceImpl的这个方法，这个service只有一个实例对象，this是单例的，相当于100个请求用的是同一个this，就能锁住了
       //

            //得到锁以后应该再去缓存中确定一次，如果没有才需要继续查询
            String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");
            if (!StringUtils.isEmpty(catalogJSON)) {
                //缓存不为null,直接返回，
                Map<String, List<Catalog2Vo>> result = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catalog2Vo>>>() {
                });
                return result;
            }
            System.out.println("重新查询了数据库");
            //将数据库多次查询变为1此
            List<CategoryEntity> selectList = this.baseMapper.selectList(null);
            //查出所有1级分类
            List<CategoryEntity> level1Category = getLevel1Catagories();
            //2、封装数据
            Map<String, List<Catalog2Vo>> parent_cid = level1Category.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
                //1、每一个的一级分类，查到这个一级分类的二级分类
                List<CategoryEntity> categoryEntities = getParentCid(selectList, v.getCatId());
                //2、封装上面的结果
                List<Catalog2Vo> catalog2Vos = null;
                if (categoryEntities != null) {
                    catalog2Vos = categoryEntities.stream().map(l2 -> {
                        Catalog2Vo catalog2Vo = new Catalog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                        //1、找当前二级分类的三级分类封装vo
                        List<CategoryEntity> level3Catalog = getParentCid(selectList, l2.getCatId());
                        if (level3Catalog != null) {
                            List<Catalog2Vo.Catalog3Vo> collect = level3Catalog.stream().map(l3 -> {
                                //2、封装成指定格式
                                Catalog2Vo.Catalog3Vo catalog3Vo = new Catalog2Vo.Catalog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                                return catalog3Vo;
                            }).collect(Collectors.toList());
                            catalog2Vo.setCatalog3List(collect);
                        }
                        return catalog2Vo;
                    }).collect(Collectors.toList());
                }
                return catalog2Vos;
            }));

            return parent_cid;

    }

    private List<CategoryEntity> getParentCid(List<CategoryEntity> selectList,Long parentCid) {
        //在selectList中找到parentId等于传入的parentCid的所有分类数据
        List<CategoryEntity> collect = selectList.stream().filter(item -> item.getParentCid() == parentCid).collect(Collectors.toList());

        return collect;
    }
}